package com.cloudcc.mobile.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.BackTrueDialog;
import com.cloudcc.mobile.entity.ContactEntity;
import com.cloudcc.mobile.entity.CustomerEntity;
import com.cloudcc.mobile.entity.KeHuMessage;
import com.cloudcc.mobile.entity.LeadEntity;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.parser.HandleParser;
import com.cloudcc.mobile.parser.KeHuParser;
import com.cloudcc.mobile.parser.ReturnCodeParser;
import com.cloudcc.mobile.service.HandleService;
import com.cloudcc.mobile.util.Json;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.weight.WeakPromptToast;
import com.mypage.utils.AnimViewUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by lin on 2017/5/11.
 */

public class NameCordKingActivity extends BaseActivity implements View.OnClickListener, BackTrueDialog.BackTrue {

    @Bind(R.id.top_back)
    ImageView topBack;
    @Bind(R.id.top_more)
    ImageView topMore;
    @Bind(R.id.top_title)
    TextView topTitle;
    @Bind(R.id.name_cord_image)
    ImageView nameCordImage;
    @Bind(R.id.top_bar_routine_layout)
    RelativeLayout topBarRoutineLayout;
    @Bind(R.id.name_cord_name_tv)
    TextView nameCordNameTv;
    @Bind(R.id.name_cord_name_ed)
    EditText nameCordNameEd;
    @Bind(R.id.name_cord_zhiwu_tv)
    TextView nameCordZhiwuTv;
    @Bind(R.id.name_cord_zhiwu_ed)
    EditText nameCordZhiwuEd;
    @Bind(R.id.name_cord_shouji_tv)
    TextView nameCordShoujiTv;
    @Bind(R.id.name_cord_shouji_ed)
    EditText nameCordShoujiEd;
    @Bind(R.id.name_cord_company_name_tv)
    TextView nameCordCompanyNameTv;
    @Bind(R.id.name_cord_company_name_ed)
    EditText nameCordCompanyNameEd;
    @Bind(R.id.name_cord_company_address_tv)
    TextView nameCordCompanyAddressTv;
    @Bind(R.id.name_cord_company_address_ed)
    EditText nameCordCompanyAddressEd;
    @Bind(R.id.name_cord_dianhua_tv)
    TextView nameCordDianhuaTv;
    @Bind(R.id.name_cord_dianhua_ed)
    EditText nameCordDianhuaEd;
    @Bind(R.id.name_cord_fax_tv)
    TextView nameCordFaxTv;
    @Bind(R.id.name_cord_fax_ed)
    EditText nameCordFaxEd;
    @Bind(R.id.name_cord_email_tv)
    TextView nameCordEmailTv;
    @Bind(R.id.name_cord_email_ed)
    EditText nameCordEmailEd;
    @Bind(R.id.name_cord_wangzhi_tv)
    TextView nameCordWangzhiTv;
    @Bind(R.id.name_cord_wangzhi_ed)
    EditText nameCordWangzhiEd;
    @Bind(R.id.name_cord_youbian_tv)
    TextView nameCordYoubianTv;
    @Bind(R.id.name_cord_youbian_ed)
    EditText nameCordYoubianEd;
    @Bind(R.id.name_cord_weaktoast)
    WeakPromptToast weakPromptToast;


    private String imagepath;//传递过来的图片地址

    public static final int INSERT_CONTACT = 100;

    private LeadEntity lead;
    private ContactEntity contact;
    private CustomerEntity kehu;
    private KeHuMessage kmg;
    private int pageSize = 15;
    private int pageNUM = 1;
    private String codes;//标记传递过来的是潜在客户还是客户  潜在客户：lead  客户: account
    private HandleService service;

    private ArrayList<HashMap<String, String>> list;//传递过来的数据

    private BackTrueDialog dialog;

    private String ids;//保存成功的id

    private boolean kehuqx, contastqx;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        getIntentMeg();
        initListener();
    }

    private void initListener() {

        topTitle.setText(getString(R.string.name_cord_title));
        topMore.setImageResource(R.drawable.selector_back_left);
        topMore.setVisibility(View.VISIBLE);
        topBack.setOnClickListener(this);
        topMore.setOnClickListener(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_name_cord;
    }

    private void getIntentMeg() {
        dialog = new BackTrueDialog(this, R.style.DialogLoadingTheme);

        Bundle bundle = getIntent().getBundleExtra("DATA");
        codes = bundle.getString("codes");
        imagepath = bundle.getString("imagepath");
        kehuqx = bundle.getBoolean("kehuqx", true);
        contastqx = bundle.getBoolean("contastqx", true);
        list = (ArrayList<HashMap<String, String>>) bundle.getSerializable("data");

        service = new HandleService();
        for (int i = 0; i < list.size(); i++) {
            HashMap<String, String> map = list.get(i);
            if (map.get("Name").equals("姓名")) {
                nameCordNameEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("职务/部门")) {
                nameCordZhiwuEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("手机")) {
                nameCordShoujiEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("公司")) {
                nameCordCompanyNameEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("地址")) {
                nameCordCompanyAddressEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("电话")) {
                nameCordDianhuaEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("传真")) {
                nameCordFaxEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("电子邮箱")) {
                nameCordEmailEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("网址")) {
                nameCordWangzhiEd.setText(map.get("Val"));
            }
            if (map.get("Name").equals("邮编")) {
                nameCordYoubianEd.setText(map.get("Val"));
            }
        }


        if (imagepath != null) {
            File file = new File(imagepath);
            if (file.exists()) {
                Uri uri = Uri.fromFile(file);
                nameCordImage.setImageURI(uri);
            }
        }

    }


    @Override
    public void onClick(View v) {

        if (v == topBack) {
            dialog.show();
        }
        if (v == topMore) {
            showWainting(getString(R.string.name_cord_saving));
            save();
        }
    }


    private void save() {
        lead = new LeadEntity();
        lead.setOwnerid(UserManager.getManager().getUser().userId);

        EditText editvalue;
        RelativeLayout layoutvalue;

        if (codes.equals("lead")) {

            String name = nameCordNameEd.getText().toString();
            String shouji = nameCordShoujiEd.getText().toString();
            if (name == null || name.length() == 0) {
                handler.sendEmptyMessage(-6);
                return;
            }
            if (shouji == null || shouji.length() == 0) {
                handler.sendEmptyMessage(-7);
                return;
            }
            lead.setName(name);// 客户名称

            lead.setCompany(nameCordCompanyNameEd.getText().toString());

            lead.setEmail(nameCordEmailEd.getText().toString());

            lead.setPhone(nameCordShoujiEd.getText().toString());

            lead.setDianhua(nameCordDianhuaEd.getText().toString());

            lead.setAddress(nameCordCompanyAddressEd.getText().toString());

            lead.setWangzhi(nameCordWangzhiEd.getText().toString());

            lead.setZhiwu(nameCordZhiwuEd.getText().toString());

            lead.setCreatebyid(UserManager.getManager().getUser().userId);
            final String aa = Json.toJson(lead);
            new Thread() {
                public void run() {
                    try {
                        String result = service.insertLead(aa);
                        if (result.equals("null") || result == null
                                || result.equals("NetworkError")) {
                            handler.sendEmptyMessage(-1);
                            return;
                        } else if (result.equals("outTime")) {
                            handler.sendEmptyMessage(-3);
                            return;
                        }
                        String code = ReturnCodeParser
                                .getReturnCode(result);
                        if (code.equals(-2)) {
                            handler.sendEmptyMessage(-2);
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(result);
                        boolean isresult = jsonObject.getBoolean("result");
                        if (isresult) {
                            String id = HandleParser.insertLeadInfo(result);
                            if (id != null) {
                                ids = id;
                                handler.sendEmptyMessage(0);
                            }
                        }
                    } catch (Exception e) {
                        Tools.handle(e);
                    }
                }

                ;
            }.start();

        } else if (codes.equals("account")) {
            contact = new ContactEntity();

            String name = nameCordNameEd.getText().toString();
            String shouji = nameCordShoujiEd.getText().toString();
            String comname = nameCordCompanyNameEd.getText().toString();
            if (name == null || name.length() == 0) {
                handler.sendEmptyMessage(-6);
                return;
            }
            if (shouji == null || shouji.length() == 0) {
                handler.sendEmptyMessage(-7);
                return;
            }
            if (comname == null || comname.length() == 0) {
                handler.sendEmptyMessage(-8);
                return;
            }
            contact.setName(name);// 联系人信息

            contact.setKhmc(comname);

            contact.setEmail(nameCordEmailEd.getText().toString());

            contact.setShouji(shouji);

            contact.setDianhua(nameCordDianhuaEd.getText().toString());

            contact.setZhiwu(nameCordZhiwuEd.getText().toString());
            contact.setFax(nameCordFaxEd.getText().toString());
            contact.setYjdz(nameCordCompanyAddressEd.getText().toString());


            // -----------------------------
            kehu = new CustomerEntity();//客户信息
            kehu.setName(nameCordCompanyNameEd.getText().toString());// 客户名称
            kehu.setDianhua(nameCordDianhuaEd.getText().toString());

            kehu.setKddz(nameCordCompanyAddressEd.getText().toString());

            kehu.setWangzhi(nameCordWangzhiEd.getText().toString());
            kehu.setFax(nameCordFaxEd.getText().toString());
            kehu.setEmail(nameCordEmailEd.getText().toString());

            if (!kehuqx) {//如果没有新建客户权限
                handler.sendEmptyMessage(INSERT_CONTACT);
                return;
            }

            // 根据客户名称搜索 如果没有这个客户新建客户 新建联系人，如果有客户，
            try {
                String b = "ORDER BY createdate Desc";
                final String expressions = "name like'%" + kehu.getName()
                        + "%' " + b;// 条件
                // 起线程 联网去查
                new Thread() {
                    @Override
                    public void run() {
                        String result = service.getAccount(pageNUM,
                                pageSize, expressions);
                        if (result == null || result.equals("null")
                                || result.equals("NetworkError")) {
                            handler.sendEmptyMessage(-1);
                            return;
                        } else if (result.equals("outTime")) {
                            handler.sendEmptyMessage(-3);
                            System.out.println("result=-3");
                            return;
                        }
                        String code = ReturnCodeParser
                                .getReturnCode(result);
                        if (code.equals(-2)) {
                            handler.sendEmptyMessage(-2);
                            return;
                        }
                        kmg = new KeHuMessage();
                        kmg = KeHuParser.getKeHu(result);
                        if (!kmg.isResult()) {
                            handler.sendEmptyMessage(-4);
                            return;
                        }
                        if (kmg.getTotalCount() == 0) {// 没有数据
                            final String kh = Json.toJson(kehu);
                            new Thread() {
                                public void run() {
                                    try {
                                        String result = service
                                                .insertAccount(kh);
                                        if (result.equals("null")
                                                || result == null
                                                || result
                                                .equals("NetworkError")) {
                                            handler.sendEmptyMessage(-1);
                                            return;
                                        } else if (result.equals("outTime")) {
                                            handler.sendEmptyMessage(-3);
                                            return;
                                        }
                                        String code = ReturnCodeParser
                                                .getReturnCode(result);
                                        if (code.equals(-2)) {
                                            handler.sendEmptyMessage(-2);
                                            return;
                                        }
                                        JSONObject jsonObject = new JSONObject(
                                                result);
                                        boolean isresult = jsonObject
                                                .getBoolean("result");
                                        if (isresult) {
                                            String id = HandleParser
                                                    .insertLeadInfo(result);
                                            if (id != null) {
                                                ids = id;
                                                contact.setKhmc(id);
                                                if (!contastqx) {//如果没有新建联系人权限
                                                    handler.sendEmptyMessage(0);
                                                } else {
                                                    handler.sendEmptyMessage(INSERT_CONTACT);
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        Tools.handle(e);
                                    }
                                }

                                ;
                            }.start();
                        } else {// 有数据
                            contact.setKhmc(kmg.getList().get(0).getId());
                            handler.sendEmptyMessage(INSERT_CONTACT);
                        }
                    }
                }.start();
            } catch (Exception e) {
                Tools.handle(e);
            }

        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_save_success));
                    Intent intent = new Intent(NameCordKingActivity.this, BeauInfoActivity.class);
                    intent.putExtra("web", ids);
                    intent.putExtra("beau.nameid", "contact");
                    intent.putExtra("callLog", "home");//只是返回变成Home按钮
                    startActivity(intent);
                    NameCordKingActivity.this.finish();
                    break;
                case -1:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail1));
                    break;
                case -2:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail2));
                    break;
                case -3:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail3));
                    break;
                case -4:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail4));
                    break;
                case -5:
                    dismissWainting();
                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail5));
                    NameCordKingActivity.this.finish();
                    break;
                case -6:
                    dismissWainting();
                    weakPromptToast.setTextTitle(getString(R.string.name_cord_fail6));
                    AnimViewUtils.getInstance().appearToast2(weakPromptToast);
//                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail6));
                    break;
                case -7:
                    dismissWainting();
                    weakPromptToast.setTextTitle(getString(R.string.name_cord_fail7));
                    AnimViewUtils.getInstance().appearToast2(weakPromptToast);
//                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail7));
                    break;
                case -8:
                    dismissWainting();
                    weakPromptToast.setTextTitle(getString(R.string.name_cord_fail8));
                    AnimViewUtils.getInstance().appearToast2(weakPromptToast);
//                    Tools.showInfo(NameCordKingActivity.this, getString(R.string.name_cord_fail8));
                    break;
                case INSERT_CONTACT:
                    new Thread() {
                        public void run() {
                            try {
                                String cc = Json.toJson(contact);
                                String rcc = service.insertContact(cc);
                                if (rcc.equals("null") || rcc == null
                                        || rcc.equals("NetworkError")) {
                                    handler.sendEmptyMessage(-1);
                                    return;
                                } else if (rcc.equals("outTime")) {
                                    handler.sendEmptyMessage(-3);
                                    return;
                                }
                                String code = ReturnCodeParser.getReturnCode(rcc);
                                if (code.equals(-2)) {
                                    handler.sendEmptyMessage(-2);
                                    return;
                                }
                                JSONObject jsonObject = new JSONObject(rcc);
                                boolean isresult = jsonObject.getBoolean("result");
                                if (isresult) {
                                    String id = HandleParser.insertLeadInfo(rcc);
                                    if (id != null) {
                                        if (TextUtils.isEmpty(ids)) {//如果没有新建客户权限，保存联系人id
                                            ids = id;
                                        }
                                        handler.sendEmptyMessage(0);
                                    }
                                }
                            } catch (Exception e) {
                                Tools.handle(e);
                            }

                        }

                        ;
                    }.start();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void rightBt() {
        finish();
    }
}
